<template>
  <div class="app-container">
    <div class="filter-condition">
      <label>条件搜索</label>
      <el-form
        size="mini"
        :inline="true"
        class="mini-form"
        style="flex: 1"
        :model="temp"
        @submit.native.prevent
      >
        <el-col :span="4">
          <el-form-item>
            <el-input
              v-model="temp.itemName"
              placeholder="任务名称"
              prefix-icon="el-icon-search"
              clearable
              @change="getPageData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select
              v-model="temp.project"
              clearable
              placeholder="请选择项目"
              @change="getPageData"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select
              v-model="temp.progress"
              clearable
              placeholder="请选择进展"
              @change="getPageData"
            >
              <el-option
                v-for="item in progressList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select
              v-model="temp.type"
              clearable
              placeholder="请选择类型"
              @change="getPageData"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-date-picker
              v-model="temp.dateOrderRange"
              value-format="yyyy-MM-dd"
              size="mini"
              type="daterange"
              align="center"
              range-separator="-"
              start-placeholder="订单开始"
              end-placeholder="订单结束"
              :picker-options="pickerOptions"
              style="width: 250px"
              @change="getPageData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-checkbox v-model="checked" @change="getPageData">未审核</el-checkbox>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <el-row>
      <el-col :span="2">
        <label class="row-label">业务操作</label>
      </el-col>
      <el-col :span="22" class="align-right">
        <dropdown-button :data="orderManageList" @click="handleOperate" />
        <dropdown-button :data="orderAddList" @click="handleAdd" />
        <el-button-group>
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdateLists"
          >
            {{ $t('table.modifyMasterInformation') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-delete"
            class="deleted-button"
            @click="handleDeletes"
          >
            {{ $t('table.batchDeletion') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            class="refresh-button"
            @click="handleRefresh"
          >
            {{ $t('table.refresh') }}
          </el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <server-table
      ref="mainTable"
      v-loading="loading"
      :style="{ height: `${commonLayoutHeight}px` }"
      :columns="columns"
      :row-data="rowData"
      operation
      show-summary
      :revoke="handleRevoke"
      :update="handleUpdate"
      :delete="handleDelete"
      @cell-value-changed="handleCellValueChanged"
      @selection-change="handleSelectionChange"
    />
    <!-- 新增 -->
    <capital-add-dialog
      :visible.sync="addDialogVisible"
      :data="temp"
      :type-list="typeList"
      :progress-list="progressList"
      :project-list="projectList"
      @add-data="handleRefresh"
    />
    <!-- 修改主信息 -->
    <modify-master-dialog
      :visible.sync="capitalVisble"
      :data="temp"
      :type-list="typeList"
      :multiple="multipleSelection"
      :progress-list="progressList"
      :project-list="projectList"
      @add-data="handleRefresh"
    />
  </div>
</template>

<script>
import NP from 'number-precision'
import { mapState } from 'vuex'
import { getConstantByType } from '@/utils/index'
import { getBasisList } from '@/api/basic-data'
import { getList, addOne, deleteOne, updateOne } from '@/api/capital'
import DropdownButton from '@/components/DropdownButton'
import capitalAddDialog from './components/capitalAddDialog.vue'
import modifyMasterDialog from './components/modifyMasterDialog.vue'

export default {
  name: 'Capital',
  components: {
    capitalAddDialog,
    DropdownButton,
    modifyMasterDialog
  },
  data() {
    return {
      dataList: [],
      constants: [],
      coordinate: [],
      multipleSelection: [],
      multipleSelectionNodes: [],
      columns: [
        {
          headerName: '审核',
          field: 'checked',
          type: 'booleanColumn'
        },
        {
          headerName: '订单号',
          field: 'cartonOrderNO'
        },
        {
          headerName: '投入日期',
          field: 'orderDate',
          type: 'dateColumn',
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'orderDate') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (params.data.operationType && params.data.operationType === 'confirm') {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          }
        },
        {
          headerName: '进展',
          field: 'progress',
          type: 'selectionColumn',
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'progress') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (
                params.data.operationType &&
                params.data.operationType === 'confirm'
              ) {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          },
          cellEditorParams: {
            list: [],
            props: { label: 'name', value: 'id' },
            select: (node, row) => {
              setTimeout(() => {
                node.data.progress = row.id
                node.data.progressName = row.name
                node.setData(node.data)
              }, 300)
            }
          }
        },
        {
          headerName: '任务名称',
          field: 'itemName',
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'itemName') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (
                params.data.operationType &&
                params.data.operationType === 'confirm'
              ) {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          }
        },
        {
          headerName: '项目',
          field: 'project',
          type: 'selectionColumn',
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'project') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (
                params.data.operationType &&
                params.data.operationType === 'confirm'
              ) {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          },
          cellEditorParams: {
            list: [],
            props: { label: 'name', value: 'id' },
            select: (node, row) => {
              setTimeout(() => {
                node.data.progress = row.id
                node.data.progressName = row.name
                node.setData(node.data)
              }, 300)
            }
          }
        },
        {
          headerName: '类型',
          field: 'type',
          type: 'selectionColumn',
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'type') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (
                params.data.operationType &&
                params.data.operationType === 'confirm'
              ) {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          },
          cellEditorParams: {
            list: [],
            props: { label: 'name', value: 'id' },
            select: (node, row) => {
              setTimeout(() => {
                node.data.type = row.id
                node.data.typeName = row.name
                node.setData(node.data)
              }, 300)
            }
          }
        },
        {
          headerName: '投入金额',
          field: 'investPrice',
          showSummary: true,
          type: 'numberColumn',
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'investPrice') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (
                params.data.operationType &&
                params.data.operationType === 'confirm'
              ) {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          }
        },
        {
          headerName: '收益金额',
          field: 'orderPrice',
          type: 'numberColumn',
          showSummary: true,
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'orderPrice') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (
                params.data.operationType &&
                params.data.operationType === 'confirm'
              ) {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          }
        },
        {
          headerName: '利润',
          field: 'profit',
          showSummary: true
        },
        {
          headerName: '利润率(%)',
          field: 'profitRate'
        },
        {
          headerName: '备注',
          field: 'remarks',
          type: 'numberColumn',
          editable: (params) => {
            return params.data.canModify === 1
          },
          cellStyle: (params) => {
            if (!params.data) return
            if (params.data.canModify === 0) {
              return { color: 'black' }
            }
            const obj = {
              field: params.colDef.field,
              rowIndex: params.node.rowIndex
            }
            const mObj = this.coordinate.find((item) => {
              return item.field === obj.field && item.rowIndex === obj.rowIndex
            })
            if (mObj && mObj.field === 'remarks') {
              return { color: 'red', fontWeight: 'bold', fontSize: '13px' }
            } else {
              if (
                params.data.operationType &&
                params.data.operationType === 'confirm'
              ) {
                return { color: 'blue', fontWeight: 'bold' }
              } else {
                return { color: 'blue' }
              }
            }
          }
        },
        {
          headerName: '修改时间',
          field: 'modifyTime',
          minWidth: 200
        },
        {
          headerName: '创建时间',
          field: 'createDate',
          minWidth: 200
        }
      ],
      rowData: {},
      temp: {
        dateOrderRange: [],
        beginDate: '',
        endDate: '',
        itemName: '',
        progress: '',
        type: '',
        project: ''
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      // 状态
      typeList: [],
      projectList: [],
      progressList: [],
      orderAddList: [
        {
          name: '新增',
          command: 'add'
        },
        {
          name: '再来一单',
          command: 'addList'
        }
      ],
      orderManageList: [
        {
          name: '审核',
          command: 'check'
        },
        {
          name: '取消审核',
          command: 'uncheck'
        }
      ],
      checked: false,
      loading: false,
      capitalVisble: false,
      addDialogVisible: false
    }
  },
  computed: {
    ...mapState('app', {
      commonLayoutHeight: state => state.height.clientHeight - 255
    })
  },
  created() {
    this.getConstant()
    this.getPageData()
  },
  methods: {
    // 表格数据
    async getPageData(parent) {
      this.loading = true
      const params = Object.assign({}, this.temp)
      if (parent && parent.page) {
        params.page = parent.page
        params.pageSize = parent.pageSize
      } else {
        params.page = 1
        params.pageSize = 100
      }
      if (this.checked) {
        params.checked = 0
      } else {
        delete params.checked
      }
      if (params.dateOrderRange) {
        params.beginDate = params.dateOrderRange[0]
        params.endDate = params.dateOrderRange[1]
      }
      delete params.dateOrderRange
      const result = await getList('getCapital', params)
      if (result.code === 200) {
        this.rowData = result.data
        this.dataList = JSON.parse(JSON.stringify(result.data.pageItems))
        setTimeout(() => {
          this.loading = false
        }, 300)
      }
    },
    // 常量
    async getConstant() {
      const result = await getBasisList('constant', { type: 1 })
      if (result.code === 200) {
        this.constants = JSON.parse(JSON.stringify(result.data.pageItems))
        this.progressList = await getConstantByType(this.constants, 7)
        const tableColumnDef = this.columns.find(column => column.field === 'progress')
        tableColumnDef.cellEditorParams.list = this.progressList
        this.projectList = await getConstantByType(this.constants, 9)
        const tableColumnDef1 = this.columns.find(column => column.field === 'project')
        tableColumnDef1.cellEditorParams.list = this.projectList
        this.typeList = await getConstantByType(this.constants, 10)
        const tableColumnDef2 = this.columns.find(column => column.field === 'type')
        tableColumnDef2.cellEditorParams.list = this.typeList
      }
    },
    // 修改
    async handleUpdate(row, e) {
      if (row.orderDate === '' || row.progress === '' || row.itemName === '' || row.project === '' || row.investPrice === '' || row.orderPrice === '') {
        return this.$message({
          showClose: true,
          message: '必选项未填！！！',
          type: 'warning',
          center: true
        })
      }
      const result = await updateOne('getCapitalUpdate', { cartonOrderNOs: [row] })
      if (result.code === 200) {
        // eslint-disable-next-line require-atomic-updates
        row.operationType = 'update'
        e.data.revoke = false
        this.clearCellStyle(e.node.rowIndex)
        this.$refs.mainTable.redrawRows()
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      }
    },
    async handleUpdateLists() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择要操作项',
          type: 'warning',
          center: true
        })
        return
      }
      const list = this.multipleSelection.filter(item => item.orderDate === '' || item.progress === '' || item.itemName === '' || item.project === '' || item.investPrice === '' || item.orderPrice === '')
      if (list.length > 0) {
        return this.$message({
          showClose: true,
          message: '必选项未填！！！',
          type: 'warning',
          center: true
        })
      }
      this.capitalVisble = true
    },
    // 删除
    async handleDelete(row) {
      this.$confirm('确认要删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const result = await deleteOne('getCapitalDelete', { cartonOrderNOs: [row.cartonOrderNO] })
        if (result.code === 200) {
          this.getPageData()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    async handleDeletes() {
      this.$confirm('确认要删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const cartonOrderNOs = this.multipleSelection.map(item => item.cartonOrderNO)
        const result = await deleteOne('getCapitalDelete', { cartonOrderNOs })
        if (result.code === 200) {
          this.getPageData()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 撤销
    handleRevoke(row, params) {
      const index = params.node.rowIndex
      row.revoke = false
      this.clearCellStyle(index)
      row.operationType = 'update'
      this.$refs.mainTable.redrawRows()
      const oldCellContent = this.dataList.find((item) => {
        return item.cartonOrderNO === row.cartonOrderNO
      })
      Object.assign(params.node.data, oldCellContent)
      this.$refs.mainTable.updateRows([params.node.data])
      this.$refs.mainTable.redrawRows()
    },
    // 状态
    async handleOperate(command) {
      if (this.multipleSelection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择要操作项',
          type: 'warning',
          center: true
        })
        return
      }
      const params = {
        cartonOrderNOs: this.multipleSelection.map(item => item.cartonOrderNO),
        checked: command === 'check' ? 1 : 0
      }
      const result = await updateOne('getCapitalCheck', params)
      if (result.code === 200) {
        this.$notify({
          title: '成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.getPageData()
      }
    },
    // 新增
    async handleAdd(command) {
      if (command === 'add') {
        this.addDialogVisible = true
      } else {
        if (this.multipleSelection.length === 0) {
          this.$message({
            showClose: true,
            message: '请选择要操作项',
            type: 'warning',
            center: true
          })
          return
        }
        if (this.multipleSelection.length > 1) {
          this.$message({
            showClose: true,
            message: '只能选择一条数据',
            type: 'warning',
            center: true
          })
          return
        }
        this.$confirm(`是否让订单号为${this.multipleSelection[0].cartonOrderNO}的数据再来一单?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const result = await addOne('getCapitalAddList', { capitalLists: this.multipleSelection })
          if (result.code === 200) {
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.getPageData()
          }
        }).catch(() => {
        })
      }
    },
    // 双击修改
    handleCellValueChanged(e) {
      // 计算规则
      // 利润 = 收益金额 — 投入金额
      // 利润率 = (利润 / 收益金额) × 100%
      if (e.value !== e.oldValue) {
        const obj = { rowIndex: e.rowIndex, field: e.colDef.field }
        this.coordinate.push(obj)
        e.data.revoke = true
        e.data.operationType = 'confirm'
        if (e.data.orderPrice) {
          e.data.profit = NP.round(NP.minus(e.data.orderPrice, e.data.investPrice), 2)
          e.data.profitRate = NP.round(NP.times(NP.divide(e.data.profit, e.data.orderPrice), 100), 2) + '%'
        }
        this.$refs.mainTable.redrawRows()
      }
    },
    // 选中数据
    handleSelectionChange(val, nodes) {
      this.multipleSelection = val
      this.multipleSelectionNodes = nodes
    },
    // 刷新
    handleRefresh() {
      setTimeout(() => {
        this.$refs.mainTable.refresh()
      }, 300)
      this.coordinate = []
    },
    clearCellStyle(index) {
      this.coordinate.map((item) => {
        if (item.rowIndex === index) {
          item.rowIndex = ''
          item.field = ''
        }
      })
    }
  }
}
</script>
